package com.atguigu.tingshu.user.strategy.impl;
import java.util.Date;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.service.VipServiceConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserVipServiceStrategy implements UpdateUserPaidRecordStrategy {
    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private VipServiceConfigService vipServiceConfigService;


    // vip购买的保存交易信息策略
    @Override
    public void updateUserPaid(UserPaidRecordVo userPaidRecordVo) {
        //防止重复消费
        LambdaQueryWrapper<UserVipService> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserVipService::getOrderNo,userPaidRecordVo.getOrderNo());
        Long aLong = userVipServiceMapper.selectCount(queryWrapper);
        if(aLong > 0) return;

        Long userId = userPaidRecordVo.getUserId();
        UserInfo userInfo = userInfoService.getUserInfoById(userId);

        //保存vip的购买信息到数据库中
        UserVipService userVipService = new UserVipService();
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setUserId(userId);

        Date now = new Date();
        if (userInfo.getIsVip().intValue() == 1 && userInfo.getVipExpireTime().after(now)){
            //是vip则开始时间等于vip的结束时间
            userVipService.setStartTime(userInfo.getVipExpireTime());
        }else {//续费
            //不是vip则开始时间等于当前时间
            userVipService.setStartTime(now);
        }

        VipServiceConfig vipServiceConfig = vipServiceConfigService.getById(userPaidRecordVo.getItemIdList().get(0));
        DateTime dateTime = DateUtil.offset(userVipService.getStartTime(), DateField.MONTH, vipServiceConfig.getServiceMonth());
        userVipService.setExpireTime(dateTime);
        userVipServiceMapper.insert(userVipService);
        //更新用户信息
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(userVipService.getExpireTime());
        userInfoService.updateById(userInfo);


    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_VIP;
    }
}
